package com.huluobo.a2212mdmdemo

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.content.Context
import android.view.animation.AccelerateInterpolator
import android.widget.ImageView
import android.widget.RelativeLayout
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.util.Timer
import kotlin.concurrent.timerTask

/**
 *  Created by LC on 2025/6/9.
 */
class RedPackView(context: Context) : RelativeLayout(context) {
    //计时器,计算间隔多长时间生成一个红包
    private lateinit var timer: Timer

    fun start() {
        timer = Timer()
        timer.schedule(timerTask {
            //开启一个协程的作用域
            CoroutineScope(Job()).launch(Dispatchers.Main) {
                val iv = ImageView(context)
                iv.setImageResource(R.drawable.liked)
                val params = LayoutParams(100, 100)
                //设置随机数,距离左侧的宽度,可以影响下雨的效果
                val num = java.util.Random().nextInt(980)
                params.topMargin = 0
                params.leftMargin = num
                iv.layoutParams = params

                val animator = ObjectAnimator.ofFloat(iv, "translationY", 0f, 1920f)
                animator.duration = 1000
                animator.interpolator = AccelerateInterpolator()
                //添加动画监听器,当动画结束时,移除view
                animator.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        super.onAnimationEnd(animation)
                        removeView(iv)
                    }
                })
                animator.start()

                //添加view到Layout上
                addView(iv)
            }
        }, 0, 100)
    }
}